<?php
namespace Api\Service;

/**
 * 主题
 */
class ThemeService
{

    public function lists()
    {
        $themes = S('themes');
        if (!$themes || true) {
            $themes = M('theme')
                ->alias('t')
                ->field('t.id,t.name,t.image')
                ->where(['t.is_delete' => 0])
                ->order('t.sort desc, t.id desc')
                ->select();

            if (count($themes)) {
                foreach ($themes as $key => $theme) {
                    $themes[$key]['goods'] = $this->goods($theme['id']);
                    unset($themes[$key]['id']);
                }
            }
            S('themes', $themes, 3600); // 缓存一小时
        }

        return $themes;
    }

    /**
     * 主题下的商品
     * @param  [type] $theme_id [description]
     * @return [type]           [description]
     */
    public function goods($theme_id)
    {
        $goods = S('theme_goods_' . $theme_id);
        if (!$goods || true) {
            $goods = M('theme_goods')
                ->alias('t')
                ->field('g.id,g.title,g.image,g.price,g.market_price,g.collect,(g.sales + g.virtual_sales) sales,g.stock')
                ->join('__GOODS__ g on t.goods_id = g.id')
                ->where([
                    't.is_delete' => 0,
                    't.theme_id'  => $theme_id,
                ])->order('t.sort desc, t.id desc')
                ->select();
            S('theme_goods_' . $theme_id, $goods, 3600); // 缓存一小时
        }

        return $goods ? $goods : [];
    }
}
